#include "providetest.h"

#include <QTest>
#include <QThreadPool>
/**
 * @brief The ReadRunner class
 * 读取线程的对象。
 */
class ReadRunner: public QRunnable{
public:
    ReadRunner(int total, ProvideTest *owner);
    // QRunnable interface
public:
    void run();
private:
    ProvideTest *m_owner;
    int m_total;
};
/**
 * @brief The WriteRunner class
 * 写入的线程对象。
 */
class WriteRunner: public QRunnable{
public:
    WriteRunner(int total, ProvideTest *owner);
    // QRunnable interface
public:
    void run();
private:
    ProvideTest *m_owner;
    int m_total;
};
ProvideTest::ProvideTest()
{

}

void ProvideTest::run()
{
    int total = 10000000; // 测试数量，越多越容易重现。

    m_list.reserve(total);
    m_list2.reserve(total);
    ReadRunner *read = new ReadRunner(total, this);
    QThreadPool pool;
    pool.start(read);

    WriteRunner *write = new WriteRunner(total, this);
    pool.start(write);
}

void ReadRunner::run()
{
    int count = m_total;
    auto fun = [](auto &item)
    {
        int size = item.size();
        if(size < 0)
        {
            QString msg = QString("Failed size:%1;cur size:%2").arg(size).arg(item.size());
            QFAIL(msg.toUtf8().data());
        }
    };
    for(int i = 0; i < count; i++){
        fun(m_owner->m_list);
        fun(m_owner->m_list2);
    }
}

void WriteRunner::run()
{
    int count = m_total;
    for(int i = 0; i < count; i++){
        m_owner->m_list.append(i);
        m_owner->m_list2.append(i);
    }
}

ReadRunner::ReadRunner(int total, ProvideTest *owner)
{
    m_total = total;
    m_owner = owner;
}

WriteRunner::WriteRunner(int total, ProvideTest *owner)
{
    m_total = total;
    m_owner = owner;
}
